﻿using System;
using System.Text;
using System.Web;
using System.IO;
using System.Web.Configuration;

namespace AjaxUploadServer
{
	public struct ServerCodeItem
	{
		public ushort code;
		public string message;
		public override int GetHashCode()
		{
			return code;
		}
		public override bool Equals(object obj)
		{
			if (obj == null) return false;
			return this.GetHashCode() == obj.GetHashCode();
		}
		public override string ToString()
		{
			return String.Format("[{0}] {1}", code, message);
		}

		public bool IsEmpty
		{
			get
			{
				return this.code == 0 && String.IsNullOrEmpty(this.message);
			}
		}

		public static ServerCodeItem Unknown
		{
			get
			{
				ServerCodeItem item = new ServerCodeItem();
				item.code = 10000;
				item.message = "Unknown error";
				return item;
			}
		}
	}

	public class ServerCode : ServerContext<ServerCode>
	{
		public ServerCode(string filename, HttpContextBase context): base(filename, context)
		{
			this.Load();
		}
		public ServerCode(string filename, IServerManager server) : base(filename, server)
		{
			this.Load();
		}
		private ServerCodeItem[] codes;
		public sealed override void Load()
		{
			var json = this.LoadJson();
			var settings = new Newtonsoft.Json.JsonSerializerSettings();
			codes = Newtonsoft.Json.JsonConvert.DeserializeObject<ServerCodeItem[]>(json, settings);
		}
		public ServerCodeItem GetItem(ushort code)
		{
			var item = Array.Find<ServerCodeItem>(codes, delegate (ServerCodeItem i)
			{
				return i.code == code;
			});
			if (item.IsEmpty)
			{
				item = ServerCodeItem.Unknown;
			}
			return item;
		}
	}
}